package com.um.jdy.common.charge.service.impl;

import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.um.springboot.starter.orm.service.BaseEntityServiceImpl;
import com.um.jdy.common.charge.service.PbOrderService;
import com.um.jdy.common.charge.dao.PbOrderDao;
import com.um.jdy.common.charge.entity.po.PbOrder;

/**
 * 服务实现类：充电宝订单扩展表
 */
@Service
@Slf4j
public class PbOrderServiceImpl extends BaseEntityServiceImpl<PbOrderDao,PbOrder>  implements PbOrderService{

    /**
     * 计算订单金额
     * @param order 订单
     * @param duration 使用时长（秒）
     * @return
     */
    @Override
    public int getChargeAmount(PbOrder order,int duration){
        //免费时长(秒)
        int freeDuration = order.getFreeDuration();

        if(duration <= freeDuration){//前面多少分钟，免费
            return 0;
        }

        //计费金额(分)
        int price = order.getPrice();
        //计费时长(秒)
        int priceDuration = order.getDuration();
        //24小时金额(分)
        int daysAmount = order.getDaysAmount();
        //封顶金额(分)
        int maxAmount = order.getMaxAmount();

        int paySeconds = getCeilTime(duration,order.getFreeDuration(),priceDuration);
        int hours24 = 24 * 3600;

        int payAmount = 0;

        while(paySeconds >= hours24){//大于24小时的，则按每个24小时来分割，再来算金额
            payAmount += daysAmount;
            paySeconds = paySeconds - hours24;
        }

        if(paySeconds > 0){
            int tempAmount = paySeconds / priceDuration * price;
            payAmount += Math.min(tempAmount,daysAmount);//当天的金额不能大于24小时金额
        }

        return Math.min(payAmount,maxAmount);//封项不能大于99元
    }

    /**
     * 不满60分钟，按60分钟收费
     *
     * @param time 租用时间（秒）
     * @param freeDuration 免费时间（秒）
     * @param priceDuration 单价计费时间(秒)
     * @return
     */
    public int getCeilTime(int time,int freeDuration,int priceDuration) {
        if(time <= freeDuration)
            return 0;

        int diff = time % priceDuration;
        return diff > 0 ? time + (priceDuration - diff) : time;
    }
}
